package com.mxpio.erp.equipment.service.impl;

import com.mxpio.erp.common.equipment.entity.*;
import com.mxpio.erp.common.equipment.service.*;
import com.mxpio.erp.common.equipment.vo.VEquipmentStockRkPosting;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.security.util.SecurityUtils;
import com.mxpioframework.system.service.impl.BaseServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @Description: 备品入库
 * @Author: jeecg-boot
 * @Date:   2021-10-07
 * @Version: V1.0
 */
@Service
public class EquipmentStockRkApplyServiceImpl extends BaseServiceImpl<EquipmentStockRkApply> implements EquipmentStockRkApplyService {

	@Resource
	private EquipmentStockRkApplyItemService tpmStockRkApplyItemService;
	@Resource
	private EquipmentStockRkHistoryService equipmentStockRkHistoryService;
	@Resource
	private EquipmentStockRejectHistoryService rejectHistoryService;
	@Resource
	private EquipmentStockItemInventoryService inventoryService;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delMain(String id) {
        JpaUtil.lind(EquipmentStockRkApplyItem.class).equal("applyId", id).delete();
        delete(EquipmentStockRkApply.class,id);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
            JpaUtil.lind(EquipmentStockRkApplyItem.class).equal("applyId", id).delete();
            delete(EquipmentStockRkApply.class,id);
		}
	}

    @Override
	@Transactional(rollbackFor = Exception.class)
    public String submit(EquipmentStockRkApply tpmStockRkApply,List<EquipmentStockRkApplyItem> itemList) {
		if (tpmStockRkApply.getStatus() == 0){
			tpmStockRkApply.setStatus(1);
		}else {
			return "只有待提交数据才可以进行提交!";
		}
		tpmStockRkApply.setVersion(tpmStockRkApply.getVersion()+1);
		this.update(tpmStockRkApply);
		itemList.forEach(item->{
			item.setStatus(1);
			item.setVersion(item.getVersion()+1);
		});
		tpmStockRkApplyItemService.update(itemList);
		return "提交成功!";
    }

	@Override
	public String changeStatus(EquipmentStockRkApply tpmStockRkApply,int status) {
		tpmStockRkApply.setStatus(status);
		tpmStockRkApply.setVersion(tpmStockRkApply.getVersion()+1);
		this.update(tpmStockRkApply);
		List<EquipmentStockRkApplyItem> itemList = tpmStockRkApplyItemService.selectByMainId(tpmStockRkApply.getId());
		itemList.forEach(item->{
			item.setStatus(status);
			item.setVersion(item.getVersion()+1);
		});
		tpmStockRkApplyItemService.update(itemList);
		return "提交成功!";
	}

    @Override
	@Transactional(rollbackFor = Exception.class)
    public synchronized void rkPosting(VEquipmentStockRkPosting tpmStockRkPostingVo) {
		List<EquipmentStockRkApplyItem> itemVoList = tpmStockRkPostingVo.getPostingItemVoList();
		if (itemVoList.size() < 1){
			return;
		}
		int type = tpmStockRkPostingVo.getType();
		AtomicBoolean isAllUpdate = new AtomicBoolean(true);
		//批量更新list
		List<EquipmentStockRkApplyItem> updateList = new ArrayList<>();
		List<EquipmentStockRkHistory> historyList = new ArrayList<>();
		List<EquipmentStockRejectHistory> rejectHistoryList = new ArrayList<>();
		//遍历详情
		itemVoList.forEach(rkItem ->{
			//接收
			if (type == 0) {
				//查询出入库单主表信息
				EquipmentStockRkApply rkApply = this.getById(EquipmentStockRkApply.class,rkItem.getApplyId());
				int remainder = rkItem.getQuantity() - rkItem.getReceivedNum();
				//判断状态是否需要更新
				if (rkItem.getThisOptNum().equals(remainder)){
					//接收完成，更新状态到2
					rkItem.setStatus(2);
					rkItem.setVersion(rkItem.getVersion()+1);
					updateList.add(rkItem);
				}else if (rkItem.getThisOptNum() > remainder){
					rkItem.setThisOptNum(remainder);
				}else {
					isAllUpdate.set(false);
				}
				//插入库存
				//查询库内是否含有同批次库位货物
				EquipmentStockItemInventory inventory = inventoryService.queryExist(rkItem.getBatchNo(), rkItem.getId(), rkItem.getMaterialsId());
				if (inventory != null) {
					inventory.setCurrentOnhandQty(inventory.getCurrentOnhandQty().add(BigDecimal.valueOf(rkItem.getThisOptNum())));
					inventory.setVersion(inventory.getVersion() + 1);
					inventoryService.update(inventory);
				} else {
					EquipmentStockItemInventory tpmStockItemInventory = new EquipmentStockItemInventory(rkApply, rkItem);
					tpmStockItemInventory.setInSysUserId(SecurityUtils.getLoginUsername());
					inventoryService.save(tpmStockItemInventory);
				}
			}else {
				//拒绝后直接修改为完成
				rkItem.setStatus(2);
				rkItem.setVersion(rkItem.getVersion()+1);
				updateList.add(rkItem);
				//拒绝，保存拒绝记录
				String reason = tpmStockRkPostingVo.getRejectReason();
				EquipmentStockRejectHistory rejectHistory = new EquipmentStockRejectHistory(rkItem.getApplyId(),0,reason);
				rejectHistoryList.add(rejectHistory);
			}
			//记录history
			EquipmentStockRkHistory history = new EquipmentStockRkHistory(rkItem,type);
			//记录关联表数据，避免自定义sql查询
			EquipmentStockRkApply stockRkApply = JpaUtil.getOne(EquipmentStockRkApply.class, rkItem.getApplyId());
			if (stockRkApply != null){
				history.setStockId(stockRkApply.getStockId());
			}
			EquipmentMaterial material = JpaUtil.getOne(EquipmentMaterial.class, rkItem.getMaterialsId());
			if(material != null){
				history.setMaterialsName(material.getName());
				history.setMaterialsCode(material.getCode());
				history.setMaterialsType(material.getProductName());
			}
			historyList.add(history);
		});
		tpmStockRkApplyItemService.update(updateList);
		equipmentStockRkHistoryService.save(historyList);
		rejectHistoryService.save(rejectHistoryList);
		//判断主表所有数据是否全部完成
		if (isAllUpdate.get()){
			List<EquipmentStockRkApplyItem> itemList = tpmStockRkApplyItemService.selectByMainId(itemVoList.get(0).getApplyId());
			AtomicBoolean doneStatus = new AtomicBoolean(true);
			itemList.forEach(item->{
				if (item.getStatus() != 2){
					doneStatus.set(false);
				}
			});
			if (doneStatus.get()){
				JpaUtil.linu(EquipmentStockRkApply.class)
						.set("status",2)
						.equal("id", itemVoList.get(0).getApplyId())
						.update();
			}
		}
    }

}
